package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IRole;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.module.entity.app.AppPortal;
import itsm.isperp.module.repository.app.AppPortalMapper;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * @date 2014-2-24
 * @author Lizx
 */
@Service
public class AppPortalService extends BaseService<AppPortal> {

	@Resource
	protected AppPortalMapper appPortalMapper;
	@Resource
	protected AppPortalRoleService appPortalRoleService;

	@Override
	public AppPortalMapper getRepository() {
		return this.appPortalMapper;
	}

	public AppPortal findOneDetail(String id) {

		AppPortal model = this.findOne(id);
		if (model != null) {
			List<String> list = appPortalRoleService.findRolesByPortalId(id);
			if (list != null) {
				int size = list.size();
				model.setRoles((String[]) list.toArray(new String[size]));
			}

		}
		return model;
	}

	public int saveOrUpdate(AppPortal entity, HttpServletRequest req) {

	  appPortalRoleService.deleteByPortalId(entity.getId());
		if (entity.getRoles() != null && entity.getRoles().length > 0)
			appPortalRoleService.saveBatch(entity.getId(), entity.getRoles());

		return super.saveOrUpdate(entity, req);

	}

	public List<AppPortal> findRolePortals(String roleId) {
		return this.appPortalMapper.findRolePortal(roleId);
	}

	public List<AppPortal> findPersonPortals(String username) {
		AppUserService appUserService = ContextHolder
				.getSpringBean(AppUserService.class);

		List<? extends IRole> rolesList = appUserService
				.findMemberRolesByUsername(username);

		if (rolesList != null && rolesList.size() > 0) {
			String[] roles = new String[rolesList.size()];

			for (int i = 0; i < roles.length; i++) {
				roles[i] = rolesList.get(i).getId();
			}
			List<AppPortal> result = this.appPortalMapper.findPersonPortal(
					username, roles);
			return result;
		}

		return null;
	}

}
